package com.cross.object;

import java.lang.reflect.Field;
import java.sql.SQLException;
import java.util.List;

import com.cross.annotation.DataCrossClass;
import com.cross.annotation.DataCrossField;
import com.cross.core.AbstractReader;
import com.cross.core.Column;
import com.cross.core.Header;
import com.cross.core.Item;
import com.cross.core.Row;

public class SimpleObjectReader  extends AbstractReader {

	private List<Object> list = null;
	
	public SimpleObjectReader(Class clazz, List list){
		this.list = list;
		this.totalIndex = list.size();
		this.rowIndex = 0;
		header = getHeader(clazz);
	}
	
	@Override
	protected boolean nextRow() {
		if(rowIndex < totalIndex){
			try {
				this.currentRow = toRow(list.get((int)rowIndex));
				rowIndex++;
				return true;
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	/**
	 * 根据ResultSetMetaData获得标题
	 * @param rsmd
	 * @return
	 * @throws SQLException
	 */
	private Header getHeader(Class clazz) {
		Header header = new Header();
		DataCrossClass dataCrossClass = (DataCrossClass) clazz.getAnnotation(DataCrossClass.class);
		header.setObjectName(dataCrossClass.objectName());
		for(Field f : clazz.getDeclaredFields()){
			DataCrossField structs = f.getAnnotation(DataCrossField.class);
			if(structs != null){
				header.add(new Column(structs.number(), structs.title(), structs.type(), structs.precision()));
			}
		}
		return header;
	}
	
	/**
	 * 将ResultSet转换为Row
	 * @param rs
	 * @return
	 * @throws SQLException
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 */
	private Row toRow(Object obj) throws IllegalArgumentException, IllegalAccessException {
		Row row = new Row();
		Class clazz = obj.getClass();
		Field[] fields = clazz.getDeclaredFields();  
		for(Field f : fields){
			DataCrossField name = f.getAnnotation(DataCrossField.class);
			if(name != null){
				Item item = new Item();
				item.setColumn(name.number());
				item.setPrecision(name.precision());
				item.setType(name.type());
				f.setAccessible(true);
				item.set(f.get(obj));
				row.append(item);
			}
		}
		return row;
	}
	
	@Override
	public void close() {
		
	}

}
